Subsetting Lists


  • Like strings ( and all the other built-in "sequence" type );
List can be "indexed" and "sliced".


  • Syntax :

    list1 = [ elem1, elem2, elem3, ... , elem(n - 1)]

    Indexing: `[ elem1, elem2, elem3, ... ]

            0    1     2
  • list1[ <starting_index> : <stopping_index> ]

                ^                 ^
            inclusive          exclusive
    
    

    i.e. include all elements from the start of the list while excluding the last element by stopping before the last element.


  • All slicing operations returns a new list containing the requested elements.
  • Assignment to slicing is also possible,

    • Caution, this could change the "size" of the list or can "clear" it completely.
  • We can also perform "negative indexing" by "prepending" a - sign before the index of a desired element from a list.
  • Syntax :

    list2 = [ elem1, elem2, elem3, ... , elem(n - 1)]

    Neagative Indexing :

    [ elem1, elem2, elem3, elem 4, elem5, elem6 ]

    -6    -5      -4      -3      -2      -1

Exercise:


  • RQ1: _Which pair of symbols do you need to do list subsetting in Python?

    Ans: Brackets: []

  • RQ2: What Python comand should you use to extract the element with index 1 from Python lsit x?

    Ans: x[1]

  • RQ3: You have a list y, containing 5 elements:

    y = ["this", "is", "a", True, "test"]

    Which two Python commands correctly extract the boolean value from the list?

    Ans: y[3] and y[-2].

  • RQ4: You want to slice a list x. The general syntax is:

    x[ begin : end ]

    • You need to replace begin and end with the indexes accroding to the slice you want to make.

    • Which of the following statements is correct?

    Ans: The begin index is "included" in the slice, and the end index is "excluded/not".

Lab: Subsetting Lists


Objectives:

  • Accessing and Extracting information from Python lists.
  • Chaning subsetting operations to access elements in lists of lists.

1) Subset and conquer -- 100xp, status:

2) Subset and calculate -- 100xp, status:

3) Slicing and dicing -- 100xp, status:

4) Slicing and dicing (2) -- 100xp, status:

5) Subsetting lists of lists -- 50xp, status:


1. Subset and conquer

  • Remember the areas list from before, containing both strings and floats? Its definition is already in the script.
  • Can you add the correct code to do some Python subsetting?

In [5]:
"""
Instructions: 

    + Print out the second element from the areas list, so 11.25.
    
    + Subset and print out the last element of areas, being 9.50.
    
        - Using a negative index makes sense here!
        
    + Select the number representing the area of the living room
      and print it out.

"""

# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0,
         "bedroom", 10.75, "bathroom", 9.50]

# Print out second element from areas
print( areas[ 1 ] )

# Print out last element from areas
print( areas[ -1 ] )

# Print out the area of the living room
print( areas[ 5 ] )


11.25
9.5
20.0

2. Subset and calculate

  • After we've extracted values from a list, we can use them to perform additional calculations.
  • Concatenation of the list elements can also be performed.

In [6]:
"""
Instructions: 

    + Using a combination of list subsetting and variable assignment,
      create a new variable, eat_sleep_area, that contains the sum of the area
      of the kitchen and the area of the bedroom.
      
    + Print this new variable "eat_sleep_area".
    
"""

# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75,
         "bathroom", 9.50]

# Sum of kitchen and bedroom area: eat_sleep_area
eat_sleep_area = areas[3] + areas[7]

# Print the variable eat_sleep_area
print( eat_sleep_area )


28.75

3. Slicing and dicing

  • Slicing means selecting multiple elemens from our list.
  • It's like splitting a list into sub-list.

In [11]:
"""
Instructions:

    + Use slicing to create a list, "downstairs", that contains the first
      6 elements of "areas".
      
    + Do a similar thing to create a new variable, "upstairs", that contains
      the last 4 elements of areas.
      
    + Print both "downstairs" and "upstairs" using print().
    
"""

# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom",
         10.75, "bathroom", 9.50]

# Use slicing to create downstairs
downstairs = areas[0:7]

# Use slicing to create upstairs
upstairs = areas[6:]

# Print out downstairs and upstairs
print( downstairs )

print( upstairs )


['hallway', 11.25, 'kitchen', 18.0, 'living room', 20.0, 'bedroom']
['bedroom', 10.75, 'bathroom', 9.5]

4. Slicing and dicing (2)

  • It is also possible to slice without explicitly defining the starting index.

    • Syntax: list1[ < undefined > : < end > ]
  • Similarly, also possible to slice without explicitly defining the ending index.

    • Syntax: list2[ begin : < undefined > ]
  • It's possible to print the entire list without defining the "begin" and "end" index of a list.

    • Syntax: list3[ < undefined > : < undefined > ]

In [15]:
"""
Instructions: 

    + Use slicing to create the lists, "downstairs" and "upstairs" again.
        
        - Without using any indexes, unless nessecery.

"""
# Create the areas list
areas = ["hallway", 11.25, "kitchen", 18.0, "living room", 20.0, "bedroom", 10.75, "bathroom", 9.50]

# Alternative slicing to create downstairs
downstairs = areas[ : 6]

# Alternative slicing to create upstairs
upstairs = areas[ 6 : ]

**5. Subsetting lists of lists

  • We can subset "lists of lists".
- Syntax: list[ [ sub-list1 ], [sub-list2], ... , [sub-list(n-1)] ]
                      0            1                     n-1

  • We can also perform both, "indexing" and "slicing" on a "lists of lists".
- Syntax: list[ < sub-list-index > ] [ < begin > : < end > ]


In [ ]:
"""
Problem definition: What will house[-1][1] return? 

"""

# Ans : float, 9.5 as the bathroom area.